# -*-coding:utf-8-*-

import pyrestful.rest
from pyrestful import mediatypes
from pyrestful.rest import get, post, put, delete
from pymongo.collection import ReturnDocument
from utils.auth import authenticated
import time, json
from datetime import datetime, timedelta
from handlers.base import BaseHandler
from tornado.gen import coroutine, Return
import tornado.concurrent
from bson.objectid import ObjectId
import functools


class ProductsHandler(BaseHandler):
    def __init__(self, application, request, **kwargs):
        super(ProductsHandler, self).__init__(application, request, **kwargs)
        self.delegate_name = 'products'

    def check_permissions(self, permissions):
        return True

    @get(_path='/platform/api/products')
    @authenticated
    @coroutine
    def get_product_list(self):
        result = yield self.delegate_get_list(self.products_dao, 'product_id')
        self.respond_success(result)

    @post(_path='/platform/api/products', _types=[dict],
          _consumes=mediatypes.APPLICATION_JSON)
    @authenticated
    @coroutine
    def create_product(self, request):
        specifics = yield self.delegate_pre_create(self.delegate_name, **request)
        if specifics is not None:
            request['specifics'] = specifics
        result = yield self.products_dao.create_product(self.user_id, request)
        self.respond_success(result)

    @put(_path='/platform/api/products/{pid}', _types=[str, dict],
         _consumes=mediatypes.APPLICATION_JSON)
    @authenticated
    @coroutine
    def update_product(self, pid, request):
        result = yield self.products_dao.update_product(self.user_id, pid, request)
        self.respond_success(result)

    @get(_path='/platform/api/products/{aspect}', _types=[str])
    @authenticated
    @coroutine
    def get_product_aspect(self, aspect):
        if 'count' == aspect:
            result = yield self.delegate_get_list(self.products_dao, 'product_id', get_count=True)
        else:
            pid = aspect
            # 需要 specifics 才能找到目标信息，比如 vendor 创建的 product，普通用户也可以获取到
            kwargs = self.query_arguments()
            filter_cond, projection = yield self.delegate_pre_get(self.delegate_name, **kwargs)
            filter_cond.update(_id=ObjectId(pid))
            result = yield self.products_dao.find_one(filter_cond, projection)
        self.respond_success(result)

    @delete(_path='/platform/api/products/{pid}', _types=[str])
    @authenticated
    @coroutine
    def delete_product(self, pid):
        result = yield self.products_dao.delete_product(self.user_id, pid)
        self.respond_success(result)

    # specifics 更新使用专用的接口
    @put(_path='/platform/api/products/{pid}/specifics', _types=[str, dict],
         _consumes=mediatypes.APPLICATION_JSON)
    @authenticated
    @coroutine
    def update_product_specifics(self, pid, request):
        kwargs = dict(specifics=request)
        handle_update = functools.partial(self.products_dao.update_product_specifics, self.user_id, pid)
        result = yield self.delegate_update(self.delegate_name, handle_update, dict(), **kwargs)
        self.respond_success(result)

    @get(_path='/platform/api/products/{pid}/specifics/{field}', _types=[str, str])
    @authenticated
    @coroutine
    def get_product_specifics(self, pid, field):
        kwargs = self.query_arguments()
        filter_cond, projection = yield self.delegate_pre_get(self.delegate_name, **kwargs)
        filter_cond.update(_id=ObjectId(pid))
        result = yield self.products_dao.find_one(filter_cond, projection)
        if 'specifics' in result and field in result['specifics']:
            result = result['specifics'][field]
        else:
            result = None
        self.respond_success(result)
